<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\WebSite;
use App\Models\WebSiteClass;
use App\Models\SearchKey;

class IndexController extends Controller
{
    // 首页
    public function index()
    {
        $websites = WebSite::orderBy('see', 'desc')->paginate(24);
        return view('index', array(
            'websites' => $websites
        ));
    }

    // 网站的介绍页面
    public function sitedetails($site_id)
    {
        $details = WebSite::find($site_id);
        $details->see = $details->see + 1;
        $details->save();
        return view('sitedetails', array(
            'details' => $details
        ));
    }

    // 网站列表
    public function sitelist(Request $request, $class_id = null)
    {
        $search = $request->input('search');

        $websiteclass = WebSiteClass::get();

        if($search != '')
        {
            // 显示搜索的关键字的网站列表
            $websites = WebSite::where('web_name', 'like' , '%'.$search.'%')->orderBy('add_time', 'desc')->simplePaginate(20);

            // 记录搜索的关键词
            $searchKey = new SearchKey();
            $searchKey->search_key = $search;
            $searchKey->ip = $request->ip();
            $searchKey->save();

            return view('site', array(
                'websites' => $websites,
                'websiteclass' => $websiteclass,
            ));
        }        

        if($class_id == null)
        {
            // 显示全部网站
            $websites = WebSite::orderBy('id', 'desc')->simplePaginate(20);
        } else {
            // 显示指定分类的网站
            $websites = WebSite::where('class_id', $class_id)->orderBy('add_time', 'desc')->simplePaginate(20);
        }       

        return view('site', array(
            'websites' => $websites,
            'websiteclass' => $websiteclass,
        ));
    }
}
